var isSelectPoint = false;
var circle = null;
var map = null;
var ORG_LIST = [];
var ORG_LIST_POINT = [];
var bts_list = [];
var bts_data_list = [];
var setLngLat = null;

function getQueryString(key) {
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return (r[2]);
    return null;
}

function onOrgClick(idx) {
    var vo = ORG_LIST[idx];
    if ((vo.x > 0) && (vo.y > 0)) {
        var pt = new BMap.Point(vo.x, vo.y);
        //创建点坐标
        map.centerAndZoom(pt, 15);

        var vIconIdx = 10;
        var vIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
            offset: new BMap.Size(11, 25), // 指定定位位置
            imageOffset: new BMap.Size(0, 0 - idx * 25) // 设置图片偏移
        });

        // 创建标注对象并添加到地图
        var vMarker = new BMap.Marker(pt, {icon: vIcon});
        vMarker.addEventListener("click", function () {
            createInfoWindow(idx);
        });
        map.addOverlay(vMarker);
    }
}

function createInfoWindow(idx) {
    var vo = ORG_LIST[idx];
    var pt = new BMap.Point(vo.x, vo.y);
    var vBody = "<div class='gis'><h4>详细信息</h4>";
    if (vo.title != null) {
        vBody = vBody + "<div class='addr'><strong>名称:</strong>" + vo.title + "</div>";
    }
    vBody = vBody + "<div class='addr'><strong>地址:</strong>" + vo.address + "</div>";
    vBody = vBody + "<div class='addr'><strong>经度:</strong>" + vo.x + "</div>";
    vBody = vBody + "<div class='addr'><strong>纬度:</strong>" + vo.y + "</div>";
    if (vo.business != null) {
        vBody = vBody + "<div class='addr'><strong>其他标签:</strong>" + vo.business + "</div>";
    }
    var vInfoWindow = new BMap.InfoWindow(vBody);
    map.openInfoWindow(vInfoWindow, pt);

    $(".active").removeClass("active")
    $("#list_" + idx).addClass("active");
    setInputLngLat(vo.x, vo.y);
}

function createInfoWindowEx(idx) {
    createInfoWindow(idx);
    loadBtsRes();
}

function createInfoWindow_point(vo) {
    var pt = new BMap.Point(vo.x, vo.y);
    var vBody = "<div class='gis'><h4>详细信息</h4>";
    if (vo.title != null) {
        vBody = vBody + "<div class='addr'><strong>名称:</strong>" + vo.title + "</div>";
    }
    vBody = vBody + "<div class='addr'><strong>地址:</strong>" + vo.address + "</div>";
    vBody = vBody + "<div class='addr'><strong>经度:</strong>" + vo.x + "</div>";
    vBody = vBody + "<div class='addr'><strong>纬度:</strong>" + vo.y + "</div>";
    if (vo.business != null) {
        vBody = vBody + "<div class='addr'><strong>其他标签:</strong>" + vo.business + "</div>";
    }
    var vInfoWindow = new BMap.InfoWindow(vBody);
    map.openInfoWindow(vInfoWindow, pt);

    $(".active").removeClass("active")
    setInputLngLat(vo.x, vo.y);
}

function initBmap(callback) {
    map = new BMap.Map("container");
    var point = new BMap.Point(121.499745, 31.236302);
    map.centerAndZoom(point, 10);
    map.enableScrollWheelZoom();
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.MapTypeControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl());
    //单击获取点击的经纬度
    map.addEventListener("click", function (e) {
        map.setDefaultCursor("url('bird.cur')");   //设置地图默认的鼠标指针样式
        if (isSelectPoint == true) {
            isSelectPoint = false;
            var pt = new BMap.Point(e.point.lng, e.point.lat);
            var vIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                offset: new BMap.Size(11, 25), // 指定定位位置
                imageOffset: new BMap.Size(0, 0 - 10 * 25) // 设置图片偏移
            });
            var vMarker = new BMap.Marker(pt, {icon: vIcon});
            map.addOverlay(vMarker);

            var myGeo = new BMap.Geocoder();
            myGeo.getLocation(pt, function (result) {
                if (result) {
                    var vs = {
                        title: null,
                        address: result.address,
                        x: e.point.lng,
                        y: e.point.lat,
                        business: result.business,
                        surroundingPois: result.surroundingPois
                    };
                    //ORG_LIST_POINT.push(vs);
                    createInfoWindow_point(vs);
                    vMarker.addEventListener("click", function () {
                        createInfoWindow_point(vs);
                    });
                }
            });
        }
    });
    //单击获取点击的经纬度
    map.addEventListener("mousemove", function (e) {
        if (isSelectPoint == false) {
            map.setDefaultCursor("url('bird.cur')");   //设置地图默认的鼠标指针样式
        }
    });

    //地图改变事件
    map.addEventListener("dragend", function (e) {
        loadBtsRes();
    });
    map.addEventListener("zoomend", function () {
        loadBtsRes();
    });

    var search = new BMap.LocalSearch("中国", {
        onSearchComplete: function (result) {
            if (search.getStatus() == BMAP_STATUS_SUCCESS) {
                var res = result.getPoi(0);
                var point = res.point;
                map.centerAndZoom(point, 11);
            }
        }, renderOptions: {
            map: map,
            autoViewport: true,
            selectFirstResult: true
        }
    });
    if (callback != null) {
        callback();
    }
}

function gisQuery() {
    var con = $("#input_content").val().replace(/(^\s+)|(\s+$)/g, "");
    $(".ersp_right").empty();
    map.clearOverlays();
    ORG_LIST = [];

    try {
        var keyword = $("#input_content").val();
        var key = keyword.replace(new RegExp("，", 'g'), ',').replace(new RegExp("；", 'g'), ';');
        var txtarr = key.split(";")
        for (var i = 0; i < txtarr.length; i++) {
            var lon = parseFloat(txtarr[i].split(",")[0]);
            var lat = parseFloat(txtarr[i].split(",")[1]);
            if (isNaN(lon) || isNaN(lat)) {
                continue;
            }

            var point = new BMap.Point(lon, lat);
            var myGeo = new BMap.Geocoder();
            myGeo.getLocation(point, function (result) {
                if (result) {
                    var vs = {
                        title: null,
                        address: result.address,
                        x: result.point.lng,
                        y: result.point.lat,
                        business: result.business,
                        surroundingPois: result.surroundingPois
                    };
                    ORG_LIST.push(vs);
                    initMapData();
                }
            });
        }
        if (ORG_LIST.length > 0) {
            var vs = ORG_LIST[0]
            createInfoWindow(0);
        }
    }
    catch (e) {
    }
    initKeyword();
}

function initMapData() {
    var con = $("#input_content").val().replace(/(^\s+)|(\s+$)/g, "");
    $(".ersp_right").empty();
    var content = "";
    for (var i = 0; i < ORG_LIST.length; i++) {
        var data = ORG_LIST[i];
        var name = data.title == null ? data.address : data.title;

        var off = -25 * i;
        content += "<dd id='list_" + i + "'>";
        content += "<a href='#' onclick='createInfoWindowEx(" + i + ")' ><i class='tip-icon' style='background-position: 0 " + off + "px;'></i>";
        if (con != "" && con != null && con.length > 0) {
            content += name.replace(con, "<span style='color:red'>" + con + '</span>');
        }
        else {
            content += name;
        }
        content += "</a></dd >";
        onOrgClick(i);
    }
    content = "<dl>" + content + "</dl>";
    $(".ersp_right").empty();
    $(".ersp_right").append(content);
}

function initData() {
    ORG_LIST = [];
    initLatLon();
    var keyword = getQueryString("keyword");
    if (keyword != null && keyword != undefined && keyword != "") {
        keyword = decodeURI(keyword);
        $("#input_content").val(keyword);
        initKeyword();
    }

}

function initLatLon() {
    var lat = getQueryString("lat");
    var lon = getQueryString("lon");

    if (lat != null && lon != null) {
        var point = new BMap.Point(lon, lat);
        map.centerAndZoom(point, 10);
        var myGeo = new BMap.Geocoder();
        myGeo.getLocation(point, function (result) {
            if (result) {
                var vs = {
                    title: null,
                    address: result.address,
                    x: result.point.lng,
                    y: result.point.lat,
                    business: result.business,
                    surroundingPois: result.surroundingPois
                };
                ORG_LIST.push(vs);
                initMapData();
                createInfoWindow(0);
            }
        });
    }
}

function getMapPoint() {
    isSelectPoint = true;
    map.setDefaultCursor("crosshair");   //设置地图默认的鼠标指针样式
    if (circle != null) {
        map.removeOverlay(circle);
    }
}

function setInputLngLat(lng, lat) {
    $("#input_lng").val(lng);
    $("#input_lat").val(lat);
    var pt = new BMap.Point(lng, lat);
    if (circle != null) {
        map.removeOverlay(circle);
    }
    circle = new BMap.Circle(pt, 500, {strokeColor: "blue", strokeWeight: 2, strokeOpacity: 0.3}); //创建圆
    map.addOverlay(circle);
    if (setLngLat != null) {
        setLngLat(lng, lat);
    }
}

function initKeyword() {
    var keyword = $("#input_content").val();
    if (keyword != null && keyword != undefined && keyword != "") {
        keyword = decodeURI(keyword);
    }

    var options = {
        onSearchComplete: function (results) {
            if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                for (var i = 0; i < results.getCurrentNumPois(); i++) {
                    var result = results.getPoi(i);
                    var vs = {
                        title: result.title,
                        address: result.address,
                        x: result.point.lng,
                        y: result.point.lat,
                        business: result.business,
                        surroundingPois: result.surroundingPois
                    };
                    ORG_LIST.push(vs);

                }
                initMapData();
                if (ORG_LIST.length > 0) {
                    createInfoWindow(0);
                    loadBtsRes();
                }
            }
        }
    };
    //map = new BMap.Map("aaaa");
    var local = new BMap.LocalSearch(map, options);
    //var local = new BMap.LocalSearch(null, options);
    local.search(keyword);
}

function setSize() {
    $('#container').height($(window).height() - $('.head').height() - 10);
}

function loadBtsRes() {
    //青空之前的基站
	return;
    for (var i = 0; i < bts_list.length; i++) {
        var g = bts_list[i];
        map.removeOverlay(g);
    }
    bts_list = [];
    if (basePath == null && basePath == "") {
        return;
    }
    $(".map-main").loading();
    var myIcon = new BMap.Icon("images/bts.png", new BMap.Size(28, 28));
    var bounds = map.getBounds();
    $.ajax({
        url: basePath + "?xmax=" + bounds.oc + "&xmin=" + bounds.rc + "&ymax=" + bounds.nc + "&?ymin=" + bounds.qc,
        data: {
            xmax: bounds.oc,
            xmin: bounds.rc,
            ymax: bounds.nc,
            ymin: bounds.qc
        },
        type: "GET",
        dataType: "json",
        success: function (req) {
            var btses = eval(req);
            if (btses != null && btses.length > 0) {
                for (var i = 0; i < btses.length; i++) {
                    var b = btses[i];
                    var point = new BMap.Point(b.longitude, b.latitude);
                    var marker = new BMap.Marker(point, {icon: myIcon});
                    marker.addEventListener("click", function (e) {
                        var b = $(this).data("data");
                        var pt = new BMap.Point(b.longitude, b.latitude);
                        var vBody = "<div class='gis'><h4>基站名称</h4>";
                        vBody = vBody + "<div class='addr'><strong>" + b.name + "</strong></div>";
                        var vInfoWindow = new BMap.InfoWindow(vBody);
                        map.openInfoWindow(vInfoWindow, pt);
                    });
                    map.addOverlay(marker);
                    bts_list.push(marker);
                    $(marker).data("data", b);
                }
            }
        },
        complete: function () {
            $(".map-main").loading("close");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
        }
    });
}

$(function () {
    $("body").keydown(function () {
        if (event.keyCode == "13") {//keyCode=13是回车键
            gisQuery();
        }
    });

    setSize();
    window.onresize = function () {
        setSize();
    };
    initBmap(function () {
        initData();
    });
})